package cn.laixueit.service.impl;

import cn.laixueit.common.RedisFInal;
import cn.laixueit.mapper.UserMapper;
import cn.laixueit.pojo.User;
import cn.laixueit.pojo.UserExample;
import cn.laixueit.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import redis.clients.jedis.Jedis;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private Jedis jedis;

    @Override
    public User login(User user) {
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        User u = userMapper.login(user);
        return u;
    }

    @Override
    public void regirest(User user) {
        // 验证码是否正确
        jedis.select(RedisFInal.INDEX);
        String redisCode = jedis.get(user.getEmail() + ":code");
        if(redisCode!=null) {
            if(redisCode.equals(user.getCode().toString())) {
                // 去数据库查询，该账号是否存在
                UserExample example = getUserExample(user);
                List<User> users = userMapper.selectByExample(example);
                // 账号不存在，注册，密码加密
                if (users.size() == 0 || CollectionUtils.isEmpty(users)) {
                    user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
                    userMapper.insertSelective(user);
                    jedis.del(user.getEmail()+":code");
                }else{
                    throw  new RuntimeException("账号已存在");
                }
            }else{
                throw  new RuntimeException("验证码错误");
            }
        }else{
            throw  new RuntimeException("验证码不存在");
        }
    }

    @Override
    public User findUserByUsername(String username) {
        User user = new User();
        user.setUsername(username);
        UserExample example = getUserExample(user);
        List<User> users = userMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(users)){
            return null;
        }
        return users.get(0);
    }

    private UserExample getUserExample(User user){
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        if(user!=null){
            if(StringUtils.isNotBlank(user.getUsername())){
                criteria.andUsernameEqualTo(user.getUsername());
            }
        }
        return example;
    }
}
